<template>
	<view class="container">
		<view class="map-container">
			<view class="title">地理位置</view>
			<view class="map-box">
				<map 
				id="gisMap" 
				:markers="currMarker" 
				:longitude="center[1]" 
				:latitude="center[0]" 
				:scale="mapScaleLevel" 
				:polygons="mapPolygon"  
				show-scale 
				enable-satellite></map>
			</view>
		</view>
		<view class="info-container">
			<view class="contract-container">
				<view class="contract-title">地块信息</view>
			</view>
			<view class="item border-line">
				<view class="subtitle">地块名称</view>
				<view>{{info.landName}}</view>
			</view>
			<view class="item border-line">
				<view class="subtitle">面积</view>
				<view>{{info.landArea}}</view>
			</view>
			<!-- <view class="item border-line">
				<view class="subtitle">人员信息</view>
				<view>{{info.person}}</view>
			</view> -->
			<!-- <view class="item border-line">
				<view class="subtitle">农户</view>
				<view>{{info.name}}</view>
			</view> -->
			<view class="item border-line">
				<view class="subtitle">管理员</view>
				<view>{{info.operatorName}}</view>
			</view>
			<view class="item border-line">
				<view class="subtitle">经纬度</view>
				<view>{{info.coords[0].lat}},{{info.coords[0].lng}}</view>
			</view>
			<view class="item border-line">
				<view class="subtitle">合同编号</view>
				<view>{{info.contractId}}</view>
			</view>
			<view class="item">
				<u-image width="100%" height="390rpx" :src="info.contract"></u-image>
			</view>
		</view>
	</view>
</template>

<script>
	import {findLandInfoByLandId} from "@/api/api.js"
	export default {
		data() {
			return {
				map:null,
				info:{},
				currentBlockId:'',
				mapScaleLevel:5,
				mapPolygon:[],
				center:[],
				currMarker:[]
			};
		},
		mounted() {
			console.log('初始化地图');
			this.map = uni.createMapContext("gisMap", this);
		},
		onLoad(routerParams) {
			this.currentBlockId = routerParams.blockId
			this.getBlockInfo();
			// this.getLocation();
		},
		methods:{
			getBlockInfo(){
				uni.showLoading({
					mask:true
				})
				let query = `landId=${this.currentBlockId}`
				findLandInfoByLandId(query).then(res=>{
					if(res?.data.code == 200){
						this.info = res.data.data
						let temp
						temp = JSON.parse(this.info.coords)
						this.info.coords = temp
						if(this.info.equipmentS){
							this.info.equipmentS.forEach(item=>{
								item["coords"] = JSON.parse(item["coords"])
							})
						}
						//设置多边形坐标
						let mapPolygons = []
						this.info.coords.forEach(item=>{
							mapPolygons.push({latitude:item.lat,longitude:item.lng})
						})
						this.mapPolygon.push({
							points:mapPolygons,
							strokeWidth:2,
							strokeColor:'#00AF99',
							fillColor:'#00AF9960'
						})
						this.calcCenter();
						uni.hideLoading()
					}else{
						uni.hideLoading()
						uni.showToast({
							icon:"none",
							title:res.data.msg
						})
					}
				}).catch(err=>{
					uni.hideLoading()
					uni.showToast({
						icon:"none",
						title:err
					})
					throw err
				})
			},
			openConfirm(){
				uni.showModal({
					title: '请求授权当前位置',
					content: '需要获取您的地理位置，请确认授权',
					success: (res)=> {
					    if (res.confirm) {
					        uni.openSetting();// 打开地图权限设置
					    } else if (res.cancel) {
							uni.showToast({
								title: '你拒绝了授权，无法获得周边信息',
								icon: 'none',
								duration: 1000
					        })
					    }
					}
				});
			},
			//保留小数工具
			toFixed(num, digits = 0) {
			  let zeroStrNum = num.toString()
			  
			  // 处理科学计算情况
			  if(zeroStrNum.includes("e")){
			     const m = zeroStrNum.match(/\d(?:\.(\d*))?e([+-]\d+)/);
			    zeroStrNum = num.toFixed(Math.max(0, (m[1] || '').length - m[2]))
			  }
			  
			  let isNegativeNum = false
			  // 判断是否为负数
			  if(zeroStrNum.startsWith('-')){
			    isNegativeNum = true
			    zeroStrNum = zeroStrNum.slice(1)
			  }
			  // 获取小数点位置
			  const dotIndex = zeroStrNum.indexOf('.')
			  // 如果是整数/保留小数位数等于超过当前小数长度，则直接用toFixed返回
			  if(dotIndex === -1 || (zeroStrNum.length - (dotIndex + 1) <= digits)){
			    return num.toFixed(digits)
			  }
			
			  // 找到需要进行四舍五入的部分
			  let numArr = zeroStrNum.match(/\d/g) || [];
			  numArr = numArr.slice(0, dotIndex + digits + 1)
			 
			  // 核心处理逻辑
			  if (parseInt(numArr[numArr.length - 1], 10) > 4) {
			    // 如果最后一位大于4，则往前遍历+1
			    for (let i = numArr.length - 2; i >= 0; i--) {
			      numArr[i] = String(parseInt(numArr[i], 10) + 1);
			      // 判断这位数字 +1 后会不会是 10
			      if (numArr[i] === '10') {
			        // 10的话处理一下变成 0，再次for循环，相当于给前面一个 +1
			        numArr[i] = '0';
			      } else {
			        // 小于10的话，就打断循环，进位成功
			        break;
			      }
			    }
			  }
			  // 将小数点加入数据
			  numArr.splice(dotIndex, 0, ".")
			  
			  // 处理多余位数
			  numArr.pop()
			  
			  // 如果事负数，添加负号
			  if(isNegativeNum){
			    numArr.unshift("-")
			  }
			  
			  return Number(numArr.join('')).toFixed(digits)  
			},
			//计算中心点
			calcCenter(){
				let points = this.info.coords
				console.log(points);
				let getCenterAVG = ()=>{
					let XAVG = 0
					let YAVG = 0
					points.forEach(item=>{
						XAVG += this.toFixed(item.lat,4)*1
						YAVG += this.toFixed(item.lng,4)*1
					})
					XAVG = XAVG/4
					YAVG = YAVG/4
					return [XAVG,YAVG]
				}
				let center =  getCenterAVG()
				console.log(center,'当前中心点');
				setTimeout(()=>{
					this.center = center
					this.mapScaleLevel = 16
					let markers = []
					if(this.info.equipmentS){
						this.info.equipmentS.forEach(item=>{
							console.log(item,'@@');
							markers.push({
								latitude:item.coords.lat,
								longitude:item.coords.lng,
								title:item.equipmentName,
								iconPath:item.icon,
								width:30,
								height:30,
								id:Math.floor(10*Math.random())+9527,
								label:{
									content:item.equipmentName,
									textAlign:'center',
									bgColor:'#edf9ff99',
									borderRadius:8,
									padding:2,
									x:-50,
									y:0
								}
							})
						})
					}
					this.currMarker = markers
				},1000)
			},
		}
	}
</script>

<style lang="scss">
.container{
	.map-container{
		background-color: #1BC46D;
		padding: 30rpx;
		.title{
			color: #ffffff;
			margin-bottom: 30rpx;
		}
		.map-box{
			width: 690rpx;
			height: 390rpx;
			border-radius: 8rpx;
			overflow:hidden;
			#gisMap{
				width:100%;
				// height: 38vh;
				height: 100%;
			}
		}
	}
	.border-line{
		border-bottom: 1rpx solid rgba(0, 0, 0, 0.12);
	}
	.info-container{
		background-color: #ffffff;
		box-shadow: 2rpx 2rpx 6rpx 2rpx #eeeeee;
		padding: 30rpx 40rpx 0 40rpx;
		.subtitle{
			font-size: 30rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #8C8C8C;
			line-height: 30rpx;
			margin-bottom: 40rpx;
		}
		.contract-container{
			.contract-title{
				font-size: 32rpx;
				font-weight: 500;
				font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
				margin-bottom: 33rpx;
				color: #1BC46D;
				font-weight: bold;
			}
			
		}
		.item{
			padding: 30rpx 0;
		}
	}
}
</style>
